package labuladong.第二章.反转链表;

import leetcode.Head;
import leetcode.ListNode;

import java.util.List;

/**
 * 反转m，n位置的链表
 */
public class Demo03 {
    static ListNode successor = null;
    public static ListNode reverseBetween(ListNode head, int m, int n) {
        if (m == 1) {
            return reverse(head, n);
        }
        head.next = reverseBetween(head.next, m-1, n-1);
        return head;
    }

    public static ListNode reverse(ListNode head, int n) {
        if (n == 1) {
            successor = head.next;
            return head;
        }
        ListNode last = reverse(head.next, n-1);
        head.next.next = head;
        head.next = successor;
        return last;
    }

    public static void main(String[] args) {
        ListNode head = Head.genListEven();
        Head.printList(reverseBetween(head, 2,4));
    }
}
